package com.liusany.myshop.security;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liusany.myshop.entity.Admin;
import com.liusany.myshop.entity.Role;
import com.liusany.myshop.service.AccountService;
import com.octo.captcha.service.CaptchaService;

public class ShiroDbRealm extends AuthorizingRealm {
	private static final Logger log = LoggerFactory.getLogger(ShiroDbRealm.class);

	@Resource
	private AccountService accountService;
	
	@Resource
	private CaptchaService captchaService;
	

	/**
	 * 构造函数设置加密 验证方式MD5加密
	 */
	@SuppressWarnings("deprecation")
	public ShiroDbRealm() {
          //setCredentialsMatcher(new Sha256CredentialsMatcher());
	      //setCredentialsMatcher(new Md5CredentialsMatcher());
	}
	 
	/**
	 * 认证回调函数, 登录时调用.
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Admin user = accountService.findUserByUsername(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUsername(),
					user.getPassword(), getName());
		} else {
			return null;
		}
	}
	
	/**
	 * 校验验证码.
	 * @author:liufei
	 * @param token 认真令牌
	 * @return
	 */
	protected boolean validateCaptcha(CaptchaUsernamePasswordToken token) {
		String captchaID = (String) SecurityUtils.getSubject().getSession().getId();
		String challengeResponse = StringUtils.upperCase(token.getCaptcha());
		if(log.isDebugEnabled())
			log.debug("校验验证码: captchaID ="+ captchaID+ ";challengeResponse="+challengeResponse);
		
		return captchaService.validateResponseForID(captchaID, challengeResponse);
	}
		
//	/**
//	 * 认证回调函数, 登录时调用.
//	 */
//	protected AuthenticationInfo doGetAuthenticationInfo(
//			AuthenticationToken authcToken) throws AuthenticationException {
//		
//		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
//		boolean isCaptcha = validateCaptcha(token);
//		if(log.isDebugEnabled())
//			log.debug("校验验证码: isCaptcha="+isCaptcha);
//		
//		if(!isCaptcha){
//			if(log.isDebugEnabled())
//				log.debug("验证码错误.");
//			
//			throw new IncorrectCaptchaException("验证码错误.");
//		}
//		Admin user = accountService.findUserByUsername(token.getUsername());
//		
//		if (user != null) {
//			if(log.isDebugEnabled())
//				log.debug("AuthenticationInfo doGetAuthenticationInfo "+ user);
//			return new SimpleAuthenticationInfo(user.getUsername(),
//					user.getPassword(), getName());
//		} else {
//			if(log.isDebugEnabled())
//				log.debug("AuthenticationInfo doGetAuthenticationInfo 失败，无用户");
//			return null;
//		}
//	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		
		String loginName = (String) principals.fromRealm(getName()).iterator()
				.next();
		Admin user = accountService.findUserByUsername(loginName);
		if (user != null) {
			if(log.isDebugEnabled())
				log.debug("AuthenticationInfo doGetAuthorizationInfo"+ user);
			
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (Role group : user.getRoleList()) {
				info.addRole(group.getName());
				info.addStringPermissions(group.getPermissionList());
			}
			return info;
		} else {
			if(log.isDebugEnabled())
				log.debug("AuthenticationInfo 失败，无用户");
			return null;
		}
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

}
